package com.jeeplus.modules.monitor.task;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.jeeplus.common.utils.HttpUtils;
import com.jeeplus.common.utils.SpringContextHolder;
import com.jeeplus.modules.monitor.entity.Task;
import net.coobird.thumbnailator.resizers.BilinearResizer;

import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.junit.Test;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonParseException;
import com.google.gson.Gson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.bidding.entity.BiddingInformation;
import com.jeeplus.modules.bidding.service.BiddingInformationService;
import com.jeeplus.modules.sys.entity.Info;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.Articles;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sys.utils.WeChatTokenUtil;
import com.jeeplus.modules.tools.utils.HttpPostTest;

@Component
public class BiddingTask extends Task {

    /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private BiddingInformationService biddingInformationService = SpringContextHolder.getBean(BiddingInformationService.class);
    @Autowired
    private SystemService systemService = SpringContextHolder.getBean(SystemService.class);

    private void sendBiddingInformation(List<BiddingInformation> list, String roleName) {
        List<String> msgList = new ArrayList<String>();
        BiddingInformation biddingInformation;
        //判断信息是否已保存，如果未保存，保存进数据库
        for (int i = 0; i < list.size(); i++) {
            biddingInformation = biddingInformationService.get(list.get(i));
            if (biddingInformation == null) {
                biddingInformationService.save(list.get(i));
            }
        }
        BiddingInformation b = new BiddingInformation();
        b.setWeChatSend("0");
        //拼写推送信息内容
        StringBuffer msg = new StringBuffer();
        StringBuffer sb = new StringBuffer();
        //取出数据库中未推送的招标信息
        List<BiddingInformation> listToSend = biddingInformationService.findList(b);
        if (listToSend.size() > 0) {
            for (int i = 0; i < listToSend.size(); i++) {
                listToSend.get(i).setWeChatSend("1");
                if (i > 0 && listToSend.get(i).getWebsite().equals(listToSend.get(i - 1).getWebsite())) {
                    sb.append(listToSend.get(i).getTitle() + "(" + listToSend.get(i).getTime() + ")\r\n");
                } else {
                    sb.append("【" + listToSend.get(i).getWebsite() + "】" + listToSend.get(i).getTitle() + "(" + listToSend.get(i).getTime() + ")\r\n");
                }
                if (sb.length() > 500) {
                    msgList.add(msg.toString());
                    sb = new StringBuffer();
                    msg = new StringBuffer();
                    if (i > 0 && listToSend.get(i).getWebsite().equals(listToSend.get(i - 1).getWebsite())) {
                        sb.append(listToSend.get(i).getTitle() + "(" + listToSend.get(i).getTime() + ")\r\n");
                    } else {
                        sb.append("【" + listToSend.get(i).getWebsite() + "】" + listToSend.get(i).getTitle() + "(" + listToSend.get(i).getTime() + ")\r\n");
                    }
                }
                msg = sb;
                if (i == listToSend.size() - 1) {
                    msgList.add(msg.toString());
                }
                biddingInformationService.save(listToSend.get(i));
            }
        } else {
            msg.append("无最新招标信息");
        }
        //获取招标员权限id
        String[] roleNames = roleName.split(",");
        StringBuffer touser = new StringBuffer();
        for (int i = 0; i < roleNames.length; i++) {
            Role role = systemService.getRoleByEnname(roleNames[i]);
            List<User> userList = systemService.getUserByRoleId(role);
            for (int j = 0; j < userList.size(); j++) {
                if (StringUtils.isNotBlank(userList.get(j).getLoginName())) {
                    if (StringUtils.isBlank(touser.toString())) {
                        touser.append(userList.get(j).getLoginName());
                    } else {
                        touser.append("|" + userList.get(j).getLoginName());
                    }
                }
            }
        }
        if (msgList.size() == 0) {
            WeChatTokenUtil.sendTextMsg(touser.toString() + "|LuJingWei", "", "", 1000002, "无最新招标信息", 0);
            WeChatTokenUtil.sendTextMsg("LuJingWei", "", "", 1000002, "发送信息给：" + touser.toString(), 0);
            logger.info("无最新招标信息");
        } else {
            for (int i = 0; i < msgList.size(); i++) {
                //推送信息给具有招标员权限的人
                WeChatTokenUtil.sendTextMsg(touser.toString() + "|LuJingWei", "", "", 1000002, msgList.get(i), 0);
                WeChatTokenUtil.sendTextMsg("LuJingWei", "", "", 1000002, "发送信息给：" + touser.toString(), 0);
                logger.info("已发送招标信息给：" + touser.toString());
//			WeChatTokenUtil.sendTextMsg("SuperAdmin", "", "", 7, msgList.get(i), 0);
            }
        }

    }

    public Document getDocument(String url) {
        try {
            Document doc = Jsoup.connect(url)
                    .header("Accept", "*/*")
                    .header("Accept-Encoding", "gzip, deflate")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0")
                    .timeout(5000)
                    .get();
            return doc;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        List<BiddingInformation> list = new ArrayList<>();

    }


    public void getXuZhou1(List<BiddingInformation> list) {
        String url = "http://218.2.208.144:8094/EBTS/publish/announcement/getList?placard_type=1";
        Map<String, String> params = new HashMap<>();
        params.put("page", "1");
        params.put("rows", "50");
        String result = HttpUtils.sendPost(url, params, "utf-8");
        JSONObject jsonObject = new JSONObject(result);
        JSONArray rows = jsonObject.getJSONArray("rows");
        for (int i = 0; i < rows.length(); i++) {
            JSONObject info = rows.getJSONObject(i);
//            if (info.getString("tender_project_type").equals("勘察设计")) {
                BiddingInformation biddingInformation = new BiddingInformation();
                biddingInformation.setWebKey(info.getString("placard_id"));
                biddingInformation.setTime(info.getString("placard_send_date"));
                biddingInformation.setTitle(info.getString("placard_name"));
                biddingInformation.setWebsite("江苏省交通运输招标投标信息管理系统");
                biddingInformation.setWeChatSend("0");
                list.add(biddingInformation);
//            }

        }
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        System.out.println(param);
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//            conn.setRequestProperty("Content-Type", "application/json");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public void run() {
        List<BiddingInformation> list = new ArrayList<BiddingInformation>();
        getXuZhou1(list);
        sendBiddingInformation(list, "vice_general_manager,general_manager");

    }
}
